<?php
namespace Home\Model;
//物品基础属性
class Worker extends UserBase{
    protected $redis;
    protected $user;
    protected $username ;
    public function __construct($user){
        parent::__construct($user, 'worker');
    }

    public function initData(){
        $this->hSet('current', 0);
        $this->addWorker('Blacksmith');
        // $this->addWorker('Carpenter');
    }

    //设置最大工人插槽//由商店升级触发
    public function setMax($num){
        $this->hSet('max', $num);
    }
    
    public function addWorker($name){
        $max = $this->getMax();
        if($max['max'] <= $max['current']) return error('工位已满');
        $pre = getPre($name);
        $old = $this->get($name);
        $info = cfg('worker', $name);
        $money = new \Home\Model\Money($this->user);
        if($old[$pre.'level']){
            $n = $info['cost'];
            if($old[$pre.'level']>1)
                $n = $n * Math.pow(1.2, $old[$pre.'level']);
            if(!$money->dec($n, 'gold', true)) return error('金钱不足购买工人2');
            $money->dec($n);
            if($old[$pre.'enable']) return error('改员工已经在工作了.');
            $this->hSet($pre.'enable', '1');
            $js = json_decode($old[$pre.'capacity'], true);
            foreach($js as $k=>$v){
                $this->add($k, $v);
            }
        }else{
            //初始化等级
           if(!$money->dec($info['cost'], 'gold', true)) return error('金钱不足购买工人1: '. $info['cost']);
           $money->dec($info['cost']);
            $this->hMset(array($pre.'level'=>'1',
                    $pre.'xp'=>'0',
                    $pre.'capacity' => json_encode($info['capacity']),
                    $pre.'point'=> '0', $pre."mastery"=>$info['mastery']));
                    foreach($info['capacity'] as $k=>$v){
                        $this->add($k, $v);
                    }
        }
        $this->hIncrBy('current', 1);

    }

    public function get($name){
        $pre = getPre($name);
        return $this->hMGet(array($pre.'level', $pre.'enable', $pre.'capacity', $pre.'skill_point', $pre.'xp', $pre.'name'));
    }
    public function getMax(){
        return $this->hMGet(array('max', 'current'));
    }
    public function add($capacity, $point){
        $this->hIncrBy($capacity, $point);
    }
    public function dec($capacity, $point){
        $this->hIncrBy($capacity, -$point);
    }
    public function getCapacity($type){
        if(is_array($type)){
            return $this->hMGet($type);
        }
        return $this->hGet($type);
    }
} 